/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.logging.Level;
import javax.swing.text.DefaultCaret;

/**
 *
 * @author pato
 */
public class Reajustar extends javax.swing.JFrame {

    /**
     * Creates new form Reajustar
     */
    PreparedStatement ps;
    ResultSet rs;
    ResultSetMetaData rsmd;
    boolean stock;
    boolean precios;
    boolean descripciones;
    boolean nuevos;
    boolean imagenes;
    public Reajustar() {
        initComponents();
        DefaultCaret caret = (DefaultCaret)textLog.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        bstock = new javax.swing.JCheckBox();
        bprecios = new javax.swing.JCheckBox();
        bdescripciones = new javax.swing.JCheckBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        textLog = new javax.swing.JTextArea();
        aceptar = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        bnuevos = new javax.swing.JCheckBox();
        imagen = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel1.setText("Reajustar Inventario");

        bstock.setText("Stock");
        bstock.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bstockActionPerformed(evt);
            }
        });

        bprecios.setText("Precios");

        bdescripciones.setText("Descripciones");
        bdescripciones.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bdescripcionesActionPerformed(evt);
            }
        });

        textLog.setColumns(20);
        textLog.setRows(5);
        jScrollPane1.setViewportView(textLog);

        aceptar.setText("Aceptar");
        aceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                aceptarActionPerformed(evt);
            }
        });

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        bnuevos.setText("Productos nuevos");

        imagen.setText("Imagenes");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(aceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jLabel1))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(bstock)
                            .addComponent(bprecios)
                            .addComponent(bdescripciones)
                            .addComponent(bnuevos)
                            .addComponent(imagen))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(bstock)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(bprecios)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(bdescripciones)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(bnuevos)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(imagen)
                        .addGap(0, 10, Short.MAX_VALUE))
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(aceptar)
                    .addComponent(jButton2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bstockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bstockActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_bstockActionPerformed

    private void aceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarActionPerformed
            
        textLog.append("Iniciando Ajuste");
stock=bstock.isSelected();
precios=bprecios.isSelected();
descripciones=bdescripciones.isSelected();
nuevos = bnuevos.isSelected();
imagenes=imagen.isSelected();
Thread cosa = new Thread() {
            public void run(){
 try {
     cache_connection.cn.setAutoCommit(false);
            local_connection.cn.setAutoCommit(false);
   if(descripciones) actualizarDescripciones();
   if(stock)actualizarStock();
   if(precios)actualizarPrecios();
   if(nuevos)actualizarNuevos();
   if(imagenes)actualizarImagenes();
    cache_connection.cn.setAutoCommit(true);
            local_connection.cn.setAutoCommit(true);
} catch (SQLException ex) {
    System.out.println(ps.toString());
    VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
}
textLog.append("\nAjuste terminado");
           aceptar.setEnabled(false);
            }
            
            };
            cosa.start();
           // this.dispose();
// TODO add your handling code here:
    }//GEN-LAST:event_aceptarActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void bdescripcionesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bdescripcionesActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_bdescripcionesActionPerformed
    void actualizarImagenes() throws SQLException{
        ps=local_connection.cn.prepareStatement("select id from archivos");
    ResultSet ns=ps.executeQuery();  
        PreparedStatement np=local_connection.cn.prepareStatement("select * from archivos where id=?");
     //   np.setInt(1,ns.getInt(1));
   // rs=ps.executeQuery();
    ps=cache_connection.cn.prepareStatement("delete from archivos");
    ps.execute();
    ps=cache_connection.cn.prepareStatement("delete from archivo_relacion");
    ps.execute();
    ps=cache_connection.cn.prepareStatement("insert into archivos values(?,?,?,?,?)");
    while(ns.next()){
        np.setInt(1,ns.getInt(1));
        rs=np.executeQuery();
        rs.next();
        ps.setInt(1,rs.getInt("id"));
        ps.setString(2,rs.getString("nombre"));
        ps.setString(3,rs.getString("ext"));
        ps.setBytes(4,rs.getBytes("archivo"));
        ps.setString(5,rs.getString("dir"));
        ps.execute();
        textLog.append("\nSe agrego la foto "+rs.getString("nombre"));
    }
    ps=local_connection.cn.prepareStatement("select * from archivo_relacion");
    rs=ps.executeQuery();
    ps=cache_connection.cn.prepareStatement("insert into archivo_relacion values(?,?)");
    while(rs.next()){
        ps.setInt(1,rs.getInt("archivoId"));
        ps.setInt(2,rs.getInt("productoId"));
        ps.execute();
        textLog.append("\nSe agrego la relacion del producto "+rs.getInt("productoId"));
    }
    local_connection.cn.commit();
            cache_connection.cn.commit();
    }
    void actualizarDescripciones() throws SQLException{
    ps=local_connection.cn.prepareStatement("select * from productos");
    rs=ps.executeQuery();
    ps=cache_connection.cn.prepareStatement("update productos set activo = ?, nombre = ?,  modelo = ?,  descripcion = ?,  especificaciones = ?,"
            + " peso = ?,  notas = ?, tipo_cantidad = ?, tipo = ?  where id_producto = ?");
  
    while(rs.next()){
          ps.setInt(1,rs.getInt("activo"));
    ps.setString(2,rs.getString("nombre"));
    ps.setString(3,rs.getString("modelo"));
    ps.setString(4,rs.getString("descripcion"));
    ps.setString(5,rs.getString("especificaciones"));
    ps.setInt(6,rs.getInt("peso"));
    ps.setString(7,rs.getString("notas"));
    ps.setString(8,rs.getString("tipo_cantidad"));
    ps.setString(9,rs.getString("tipo"));
    ps.setInt(10,rs.getInt("id_producto"));
    textLog.append("\nSe corrigieron las propiedades del producto "+rs.getInt("id_producto"));
    ps.execute();
    }
    local_connection.cn.commit();
            cache_connection.cn.commit();
}
void actualizarPrecios() throws SQLException{
    ps=local_connection.cn.prepareStatement("select * from precios where sucursal = ?");
     ps.setInt(1,VentanaPrincipal.sucursal);
    rs=ps.executeQuery();
    ps=cache_connection.cn.prepareStatement("delete from precios");
    ps.execute();
    ps=cache_connection.cn.prepareStatement("insert into precios values(?,?,?,?,?)");
    while(rs.next()){
        ps.setInt(1,rs.getInt("id_producto"));
        ps.setString(2,rs.getString("nombre"));
        ps.setInt(3,rs.getInt("cantidad"));
        ps.setDouble(4,rs.getDouble("precio"));
        ps.setInt(5,rs.getInt("sucursal"));
        ps.execute();
        textLog.append("\nSe corrigieron los precios del producto "+rs.getInt("id_producto"));
    }
    local_connection.cn.commit();
            cache_connection.cn.commit();
}
void actualizarStock() throws SQLException{
     ps=local_connection.cn.prepareStatement("select * from stock where sucursal = ?");
     ps.setInt(1,VentanaPrincipal.sucursal);
    rs=ps.executeQuery();
    ps=cache_connection.cn.prepareStatement("delete from stock");
    ps.execute();
    ps=cache_connection.cn.prepareStatement("insert into stock values(?,?,?,?,?)");
    while(rs.next()){
        ps.setInt(1,rs.getInt("id_producto"));
        ps.setInt(2,rs.getInt("cantidad"));
        ps.setString(3,rs.getString("ubicacion"));
        ps.setInt(4,rs.getInt("sucursal"));
        ps.setInt(5,rs.getInt("minimo"));
        ps.execute();
        textLog.append("\nSe corrigio el stock del producto "+rs.getInt("id_producto"));
    }
    local_connection.cn.commit();
            cache_connection.cn.commit();
}
void actualizarNuevos() throws SQLException{
    int ultimo = 0;
    String signos="?";
    ps=cache_connection.cn.prepareStatement("select id_producto from productos order by id_producto desc limit 1");
    rs=ps.executeQuery();
    if(rs.next()) ultimo = rs.getInt(1);
    ps=local_connection.cn.prepareStatement("select * from productos where id_producto > ?");
    ps.setInt(1,ultimo);
    rs=ps.executeQuery();
    rsmd = rs.getMetaData();
    int columnsNumber = rsmd.getColumnCount();
    for(int i=1;i<columnsNumber;i++)
        signos+=",?";
    ps=cache_connection.cn.prepareStatement("Insert into productos values("+signos+")");
    while(rs.next()){
        for(int i=1;i<=columnsNumber;i++)
        ps.setObject(i,rs.getObject(i));
        ps.execute();
    }
    local_connection.cn.commit();
            cache_connection.cn.commit();
            }
    /**
     * @param args the command line arguments
     */
  
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton aceptar;
    private javax.swing.JCheckBox bdescripciones;
    private javax.swing.JCheckBox bnuevos;
    private javax.swing.JCheckBox bprecios;
    private javax.swing.JCheckBox bstock;
    private javax.swing.JCheckBox imagen;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea textLog;
    // End of variables declaration//GEN-END:variables
}
